// ElectronicFenceController.java
package cn.tedu.smartos.family_user.controller;


import cn.tedu.smartos.base.response.JsonResult;
import cn.tedu.smartos.family_user.pojo.dto.FenceParam;
import cn.tedu.smartos.family_user.pojo.vo.ElectronicFenceVO;
import cn.tedu.smartos.family_user.pojo.vo.PositionAlertVO;
import cn.tedu.smartos.family_user.service.FenceService;
//import cn.tedu.smartos.family_user.service.impl.CustomUserDetails;
import cn.tedu.smartos.family_user.service.PositionAlertService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "电子围栏与预警管理")
@Slf4j
@RestController
@RequestMapping("/api/v1/family_user/fence")
public class ElectronicFenceController {

    @Autowired
    private FenceService fenceService;
    @Autowired
    private PositionAlertService positionAlertService;

    @ApiOperation("创建电子围栏")
    @ApiOperationSupport(order = 10)
    @PostMapping( "add")
    public JsonResult createFence(@Valid @RequestBody FenceParam param) {
        log.info("创建电子围栏, 家属ID: {}, 老人ID: {}",
                param.getFamilyUserId(), param.getElderlyUserId());
        fenceService.createFence(param);
        return JsonResult.ok("围栏创建成功");
    }

    @ApiOperation("更新电子围栏")
    @ApiOperationSupport(order = 20)
    @PutMapping("/update/{fenceId}")
    public JsonResult updateFence(
            @PathVariable Long fenceId,
            @RequestBody FenceParam param) {
        log.info("更新电子围栏, ID: {}", fenceId);
        param.setFenceId(fenceId); // 设置参数中的fenceId
        fenceService.updateFence(param);
        return JsonResult.ok("围栏更新成功");
    }

//    // 使用 Spring Security 认证
//    private Long getCurrentUserId() {
//        var authentication = SecurityContextHolder.getContext().getAuthentication();
//        if (authentication == null || !authentication.isAuthenticated()) {
//            throw new ServiceException(StatusCode.UNAUTHORIZED, "用户未登录");
//        }
//
//        Object principal = authentication.getPrincipal();
//        if (principal instanceof CustomUserDetails) {
//            CustomUserDetails userDetails = (CustomUserDetails) principal;
//            log.info("获取当前用户ID: {}", userDetails.getId());
//            return userDetails.getId();
//        } else {
//            throw new ServiceException(StatusCode.UNAUTHORIZED, "无效的用户身份");
//        }
//    }

    @ApiOperation("删除电子围栏")
    @ApiOperationSupport(order = 30)
    @DeleteMapping("/delete/{fenceId}")
    public JsonResult deleteFence(@PathVariable Long fenceId) {
//        Long currentUserId = getCurrentUserId(); // 获取当前登录用户ID
//        log.info("删除电子围栏, ID: {}, 操作者: {}", fenceId, currentUserId);
//        fenceService.deleteFence(fenceId, currentUserId);
//        return JsonResult.ok("围栏删除成功");

        fenceService.deleteFence(fenceId);
        return JsonResult.ok("围栏删除成功");
    }

    @ApiOperation("查询家属设置的围栏列表")
    @ApiOperationSupport(order = 40)
    @GetMapping("/family/{familyUserId}")
    public JsonResult getFencesByFamily(@PathVariable Long familyUserId) {
        log.info("查询家属设置的围栏, 家属ID: {}", familyUserId);
        List<ElectronicFenceVO> fences = fenceService.getFencesByFamily(familyUserId)
                .stream()
                .map(ElectronicFenceVO::new)
                .collect(Collectors.toList());
        return JsonResult.ok(fences);
    }

    @ApiOperation("查询老人所有围栏")
    @ApiOperationSupport(order = 50)
    @GetMapping("/elderly/{elderlyUserId}")
    public JsonResult getFencesByElderly(@PathVariable Long elderlyUserId) {
        log.info("查询老人围栏, 老人ID: {}", elderlyUserId);
        List<ElectronicFenceVO> fences = fenceService.getFencesByElderly(elderlyUserId)
                .stream()
                .map(ElectronicFenceVO::new)
                .collect(Collectors.toList());
        return JsonResult.ok(fences);
    }

    @ApiOperation("查询单个围栏详情")
    @ApiOperationSupport(order = 60)
    @GetMapping("/select/{fenceId}")
    public JsonResult getFenceById(@PathVariable Long fenceId) {
        log.info("查询围栏详情, ID: {}", fenceId);
        ElectronicFenceVO fence = new ElectronicFenceVO(fenceService.getFenceById(fenceId));
        return JsonResult.ok(fence);
    }

    @ApiOperation("获取老人位置越界预警记录")
    @ApiOperationSupport(order = 70)
    @GetMapping("/alerts/{elderlyUserId}")
    public JsonResult getPositionAlerts(
            @ApiParam(value = "老人用户ID", required = true)
            @PathVariable Long elderlyUserId,

            @ApiParam(value = "返回记录数量，默认10条")
            @RequestParam(required = false, defaultValue = "10") Integer limit
    ) {
        log.info("查询老人位置越界预警记录, 老人ID: {}, 数量: {}", elderlyUserId, limit);
        List<PositionAlertVO> alerts = positionAlertService.getAlertsByElderly(elderlyUserId, limit);
        return JsonResult.ok(alerts);
    }

    @ApiOperation("处理位置预警")
    @ApiOperationSupport(order = 80)
    @PutMapping("/alerts/handle/{alertId}")
    public JsonResult handleAlert(
            @ApiParam(value = "预警ID", required = true)
            @PathVariable Long alertId
    ) {
        log.info("处理位置预警: ID={}", alertId);
        positionAlertService.handleAlert(alertId);
        return JsonResult.ok("预警已处理");
    }
}